import request from '@/utils/request';
import {
  ChatMessage,
  ChatRequest,
  ChatResponse,
  ChatSession,
  ChatSessionDetail,
  ChatSessionParams,
  CreateChatSessionRequest,
  UpdateChatSessionRequest,
  ChatSessionListResponse,
  ChatSessionPageResponse,
  ChatSessionDetailResponse,
  ChatSessionResponse,
  ChatCompletionResponse,
  DeleteChatSessionResponse,
  ClearAllChatResponse
} from '@/types/chat';

// 发起聊天对话
export const sendChatMessage = (params: ChatRequest): Promise<ChatCompletionResponse> => {
  return request.post('/api/client/chat/completions', params);
};

// 获取聊天会话列表（简单列表）
export const getChatSessionList = (params: ChatSessionParams): Promise<ChatSession[]> => {
  return request.post('/api/client/chat/sessions/list', params);
};

// 获取聊天会话列表（分页）
export const getChatSessionPage = (params: ChatSessionParams): Promise<{
  data: ChatSession[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
  hasNextPage: boolean;
  hasPrevPage: boolean;
}> => {
  return request.post('/api/client/chat/sessions/page', params);
};

// 获取单个聊天会话详情
export const getChatSessionDetail = (chatId: string): Promise<ChatSessionDetail> => {
  return request.post('/api/client/chat/sessions/detail', { chatId });
};

// 创建新的聊天会话
export const createChatSession = (params: CreateChatSessionRequest): Promise<ChatSession> => {
  return request.post('/api/client/chat/sessions/create', params);
};

// 更新聊天会话（标题、置顶状态等）
export const updateChatSession = (chatId: string, params: UpdateChatSessionRequest): Promise<ChatSession> => {
  return request.post('/api/client/chat/sessions/update', { chatId, ...params });
};

// 删除聊天会话
export const deleteChatSession = (chatId: string): Promise<{ message: string }> => {
  return request.post('/api/client/chat/sessions/delete', { chatId });
};

// 清空所有聊天历史记录
export const clearAllChatHistory = (): Promise<{
  message: string;
  deletedCount: number;
  deletedMessagesCount: number;
}> => {
  return request.post('/api/client/chat/sessions/clear', {});
};

// 流式聊天（返回 ReadableStream）
export const sendChatMessageStream = async (params: ChatRequest): Promise<ReadableStream> => {
  const response = await fetch('/api/client/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${localStorage.getItem('token')}`, // 假设token存储在localStorage
    },
    body: JSON.stringify({
      ...params,
      stream: true
    })
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  if (!response.body) {
    throw new Error('Response body is null');
  }

  return response.body;
};
